package org.hibernate.tool.ipan.format;

import java.util.HashMap;
import java.util.Map;

import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.ToolFactory;
import org.eclipse.jdt.core.formatter.CodeFormatter;
import org.eclipse.jface.text.Document;
import org.eclipse.jface.text.IDocument;
import org.eclipse.text.edits.TextEdit;

/**
 * Java代码格式化工具
 * 
 * @author iPan
 * @version 2013-12-8
 */
public class JavaCodeFormatter {
	
	private static CodeFormatter formatter = null;
	
	public static synchronized CodeFormatter getFormatter() {
		if (formatter == null) {
			Map<String, String> hashMap = new HashMap<String, String>();
			hashMap.put( JavaCore.COMPILER_SOURCE, "1.5");
			hashMap.put( JavaCore.COMPILER_COMPLIANCE, "1.5");
			hashMap.put( JavaCore.COMPILER_CODEGEN_TARGET_PLATFORM, "1.5");
			formatter = ToolFactory.createCodeFormatter(hashMap);
		}
		return formatter;
	}

	public static String defaultFormat(String source) {
		TextEdit edit = getFormatter().format(CodeFormatter.K_COMPILATION_UNIT, source, 0, source.length(), 0, null);
		if (edit == null) {
			return source;
		}
		IDocument doc = new Document();
		doc.set(source);
		try {
			edit.apply(doc);
		} catch (Exception e) {
			return source;
		}
		return doc.get();
	}
	
	public static void main(String[] args) {
		String text = "public class Test<T> {" 
					+ "/** name */private String name=\"你好世界！\";"
					+ "/** obj */private T obj;/**say*/public void say() {"
					+ "System.out.println(name);}/**getObj*/public T getObj() {return obj;}}";
		System.out.println(JavaCodeFormatter.defaultFormat(text));
	}
}
